package com.base.util;

import com.base.CoreConstants;
import com.base.oss.MyOssClient;
import com.base.web.annotation.LoginMethod;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

public class ToolsUtil {

	/**
	 * 获取session数据
	 */
	public static Object getSessionParameter(String name) {
		Object obj = RequestUtils.getRequest().getSession().getAttribute(LoginMethod.ADMIN.getName());
		if (obj != null) {
			HashMap map = (HashMap) obj;
			return map.get(name);
		} else {
			return null;
		}
	}
	
	/**
	 * 获取UUID随机码[true:保留原有样式 false:不保留，去除其中的-]
	 */
	public static String getUUID(boolean flag) {
		String uuid = UUID.randomUUID().toString();
		if (!flag) {
			uuid = uuid.replaceAll("-", "");
		}
		return uuid;
	}
	
	/**
     * 填充字符至指定位数，前面加0
     * @param aa
     * @param nums
     * @return
     */
    public static String fillZero(String aa, int nums) {
    	if (aa == null || "".equals(aa.trim())) {
    		return null;
    	}
    	StringBuffer buf = new StringBuffer(aa);
    	while (buf.length() < nums) {
    		buf.insert(0, 0);
    	}
    	return buf.toString();
    }
    
    /**
     * 获取指定长度的随机英文字母
     * @param length
     * @return
     */
    public static String getRandomString(int length)
    {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < length; i++)
        {
            int number = random.nextInt(52);
            sb.append(str.charAt(number));
        }

        return sb.toString();
    }
    
    /**
	 * 传输参数替换占位符，返回一字符串
	 */
	public static String getPlaceholderStr(String str, Object... objects) {
		if (StringUtil.isBlank(str)) {
			return "";
		}
		return MessageFormat.format(str, objects);
	}
	
	/**
	 * 使用指定字符分隔字符串集合，返回一字符串
	 */
	public static String getStrWithChar(List<?> list, String c) {
		if (list == null || list.size() == 0) {
			return null;
		}
		if (list.size() == 1) {
			return list.get(0).toString();
		}
		if (StringUtil.isBlank(c)) {
			c = ",";
		}
		StringBuffer buf = new StringBuffer();
		for (Object ele : list) {
			buf.append(ele).append(c);
		}
		return buf.length() > 0 ? buf.substring(0, buf.length() - 1) : "";		
	}
	
	/**
	 * 根据文件存储方式获取文件流
	 */
	public static InputStream getFileStream(String belong, String path) throws Exception {
		InputStream is;
		if (MyOssClient.getHead().equals(belong)) {
			is = MyOssClient.getObjectStream(path, null);
		}
//		else if (MyCosClient.getBelong().equals(belong)) {
//			is = MyCosClient.getFileStream("/" + path);
//		}
		else {
			is = new FileInputStream(new File(new StringBuilder()
					.append(CoreConstants.FILE_PATH).append("/")
					.append(path).toString()));
		}
		return is;
	}

}
